import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, FormGroup, Validators, MinLengthValidator } from '@angular/forms';

@Component({
  selector: 'app-angular-day4-selector',
  templateUrl: './angular-day4.component.html',
  styleUrl: './angular-day4.component.css'
})
export class AngularDay4Component implements OnInit {

  ngOnInit(): void {
    
  }

  constructor(private B: FormBuilder){}

  valiDataForm: FormGroup = this.B.group(
    {username:['', [Validators.required,Validators.maxLength(18), Validators.minLength(6)]  ],
    password: ['', [Validators.required, this.passWordVal]],
    phone : ['', [Validators.required, this.phoneVal],]}
  );

  passWordVal(password:FormControl):object{
    let value = password.value || '';
    if(!value){
      return {msg : '请输入密码'}
    }
    else{
      const valid = value.match(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/);
      return valid?{}:{msg:'密码格式不正确'}
    }
  }

  phoneVal(phone:FormControl):object{
    const value = phone.value || '';
    if (!value) return {desc:'请输入手机号'}
    const valid = value.match(/^[0-9]{11}$/);
    return valid ? {}:{desc : '手机号必须是11位数字'}
  }

  CulculateStringCount(input:string):number{
    return input.length
  }

  GetActualPhoneErrorMsg():string{
    return this.valiDataForm.get('phone')?.errors?.['desc'] + ";but actual number is :" + this.CulculateStringCount(this.valiDataForm.get('phone')?.value)
  }

  subvaliDataFormFun(){
    console.log("--------------valiDataForm info-----------------------");
    console.log(this.valiDataForm);
    console.log("--------------username info-----------------------");
    console.log(this.valiDataForm.get('username'));
    console.log("username value is :" + this.valiDataForm.get('username')?.value);
    console.log("username valid :" + this.valiDataForm.get('username')?.valid);
    console.log("username status :" + this.valiDataForm.get('username')?.status);
    console.log("username minlength :" + this.valiDataForm.get('username')?.errors?.['minlength']?.requiredLength);
    console.log("username maxlength :" + this.valiDataForm.get('username')?.errors?.['maxlength']?.['requiredLength']);
    console.log("--------------password info-----------------------");
    console.log("password msg :" + this.valiDataForm.get('password')?.errors?.['msg']);

    console.log("--------------phone info-----------------------");
    console.log("phone msg(desc) :" + this.valiDataForm.get('phone')?.errors?.['desc']);
    console.log("phone's value :" + this.valiDataForm.get('phone')?.value);
  }
}
